package Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "sessionFilter", urlPatterns = "/*")
public class SessionFilter implements Filter
{

    private String[] filterExclusionUrls = {"/API/User/Register","/API/User/Login","/signup.jsp","/index.jsp", "/css/style.css","/js/sweetalert/sweet-alert.js","/js/sweetalert/sweet-alert.css","/js/datatables/dataTables.bootstrap4.js"
    ,"/css/datatables/jquery.dataTables.css","/js/datatables/jquery.dataTables.js","/js/jquery.min.js","/css/bootstrap.css",
    "/css/font-awesome.min.css","/js/app.js","/js/app.plugin.js","/js/bootstrap.js","/js/app.data.js","js/moment.js","js/echarts.min.js"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();
        String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        if (isFliter(url)) {
            //检查是否有Token
            if (session.getAttribute("Token") != null) {
                chain.doFilter(request, response);
                System.out.println(url);
                return;
            } else {
                // Token不存在的话
                request.getRequestDispatcher("index.jsp").forward(request,response);
            }
        } else {
            chain.doFilter(request, response);
            return;
        }

    }
    private boolean isFliter(String url) {
        for (String exclusion : filterExclusionUrls) {
            if (exclusion.equals(url)) {
                return false;
            }
        }
        return true;
    }
}
